#include "../include/Configuration.h"
#include "../include/Logger.h"
#include <fstream>

using std::ifstream;

namespace myNameSpace {
Configuration *Configuration::_pInstance = nullptr;
pthread_once_t Configuration::_once = PTHREAD_ONCE_INIT;

Configuration *Configuration::getInstance() {
    pthread_once(&_once, init);
    return _pInstance;
}

void Configuration::read(const string &filename) {
    ifstream ifs(filename);
    if (!ifs.good()) {
        moqi::LOG_ERROR("Open file %s failed.", filename.c_str());
        exit(EXIT_FAILURE);
    }
    string key, value;
    while (ifs >> key >> value) {
        _map[key] = value;
    }
    ifs.close();
}

string Configuration::getValue(const string &key) {
    auto it = _map.find(key);
    if (it == _map.end()) {
        moqi::LOG_ERROR("%s is not found in conf.", key.c_str());
        exit(EXIT_FAILURE);
    }
    return it->second;
}

Configuration::Configuration() {
    moqi::LOG_INFO("Configuration()");
}

Configuration::~Configuration() {
    moqi::LOG_INFO("~Configuration()");
}

void Configuration::init() {
    if (!_pInstance) {
        _pInstance = new Configuration();
        atexit(destroy);
    }
}

void Configuration::destroy() {
    if (_pInstance) {
        delete _pInstance;
        _pInstance = nullptr;
    }
}
} // end of namespace myNameSpace
